package org.springframework.boot.tests.hibernate52.mytest.beanFactorypostProcessor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.tests.hibernate52.mytest.annotation.Chris;
import org.springframework.context.annotation.ScannedGenericBeanDefinition;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.MethodMetadata;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * BeanFactoryPostProcessor接口的本意只是修改或添加Bean定义，甚至可以去初始化实例
 */
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

	protected final Log logger = LogFactory.getLog(getClass());

	/**
	 * 我们这里取出装有{@link Chris}注解的bean定义，进行实例化
	 *
	 * @param beanFactory
	 * @throws BeansException
	 */
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
			throws BeansException {
		String[] beanNamesForAnnotation = beanFactory.getBeanNamesForAnnotation(Chris.class);
		for (String beanName : beanNamesForAnnotation) {
			BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
			if (beanDefinition instanceof ScannedGenericBeanDefinition) {
				AnnotationMetadata metadata = ((ScannedGenericBeanDefinition) beanDefinition).getMetadata();
				Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(Chris.class.getName());
				if(annotationAttributes!=null){
					boolean lazy = (boolean)annotationAttributes.get("lazy");
					if(lazy){
						logger.info(beanName+ "lazy");
						continue;
					}
					beanFactory.getBean(beanName);
				}
			}
		}
	}
}
